/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package knowledgebase.service;

import java.util.List;
import knowledgebase.dao.UserDAO;
import knowledgebase.model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 *
 * @author eugene
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    Log log = LogFactory.getLog(getClass());
    @Autowired
    private UserDAO dao;
    @Autowired
    private ReflectionSaltSource saltSource;
    @Autowired
    private RoleService roleService;
    private ShaPasswordEncoder sha = new ShaPasswordEncoder(512);;

    public void setDao(UserDAO dao) {
        this.dao = dao;
    }

    @Override
    public List<User> getAllUser() {
        return dao.getAllUser();
    }

    @Override
    public void saveOrUpdateUser(User user) throws Exception {
        user.setPassword(sha.encodePassword(user.getPassword(), saltSource.getSalt(new Assembler(user))));
        if(user.getRoles().isEmpty()) {
            user.getRoles().add(roleService.getRoleByName("ROLE_READER"));
        }
        try {
            dao.saveOrUpdateUser(user);
        } catch (Exception ex) {
            String message = "";
            Throwable throwable = ex;
            do {
                if (throwable.getMessage().indexOf("UK_USER_NAME") != -1) {
                    message = "User with the same name already exists";
                    log.error(message + "\n" + ex);
                } else if (throwable.getMessage().indexOf("UK_EMAIL") != -1) {
                    message = "User with the same email address already exists";
                    log.error(message + "\n" + ex);
                }
            } while ((throwable = throwable.getCause()) != null);
            throw new Exception(message, ex);
        }
    }

    @Override
    public void removeUserById(long userId) {
        dao.removeUserById(userId);
    }

    @Override
    public User findUserByName(String name) {
        return dao.findUserByName(name);
    }
    
    @Override
    public List<User> searchUser(String name, String email, Boolean isEnabled, int startIndex, int size){
        return dao.searchUsers(name, email, isEnabled, startIndex, size);
    }
    
    @Override
    public long getUserCount() {
        return dao.getUserCount();
    }
}
